package top.rtfsc8.demo.shiro.realm;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;

public class MyRealm2 
	implements Realm {
	
	private Log logger = LogFactory.getLog(getClass());

	@Override
	public String getName() {
		return "myRealm2";
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UsernamePasswordToken;
	}

	@Override
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) 
			throws AuthenticationException {
		logger.info("@@ get authentication info:");
		// 获取用户名
		String username = (String) token.getPrincipal();
		// 获取密码
		String password = new String((char[]) token.getCredentials());
		logger.info("@@ username=" + username + ", password=" + password);
		if (! "wang.ermazi".equals(username) 
				|| ! "123456".equals(password)) {
			logger.error("用户名或密码错误！");
			throw new UnknownAccountException("用户名或密码错误！");
		}
		// 身份认证成功则返回一个AuthenticationInfo实现
		return new SimpleAuthenticationInfo(username, password, getName());
	}

}
